package com.rd.config.security;

import cn.hutool.json.JSONUtil;
import com.rd.util.ResultUtil;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.AuthenticationEntryPoint;
import org.springframework.stereotype.Component;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 *用于处理未认证通过的用户请求的入口点
 */
@Component
public class JwtAuthenticationEntryPoint implements AuthenticationEntryPoint {
    @Override
    public void commence(HttpServletRequest request, HttpServletResponse response,
                         AuthenticationException authException) throws IOException, ServletException {
        response.setContentType("application/json;charset=utf-8");
        // 401 需要用户身份验证
        String errMsg="访问失败,请进行身份验证！";
        if(authException !=null){
            errMsg= authException.getMessage();
        }
        String backStr = JSONUtil.toJsonStr(ResultUtil.buildError(401,errMsg));
        response.getWriter().write(backStr);
    }
}
